package com.doge.walknovel.utils

import android.util.LruCache

private val imageCache = LruCache<String, String>(80)

fun thumbnail(url: String?, width: Int, height: Int, type: Int, quality: Int = 75): String? {
    if (!opt(url)) return url // maybe user avatar url startWith http://graph.facebook.com/
    val cacheKey = "$url-$width-$height-$type-$quality"
    val result = imageCache[cacheKey]
    if (!result.isNullOrEmpty()) return result
    // https://docs.ucloud.cn/storage_cdn/ufile/service/pic
    val processedUrl = if (width == 0 && height == 0) {
        "$url?iopcmd=convert&dst=webp&Q=$quality"
    } else {
        "$url?iopcmd=convert&dst=webp&Q=$quality|iopcmd=thumbnail&type=$type&width=$width&height=$height"
    }
    return processedUrl.also {
        imageCache.put(cacheKey, it)
    }
}

private fun opt(url: String?): Boolean {
    if (url.isNullOrEmpty()) return false
    if (!url.startsWith("http")) return false
    if (url.startsWith("http://walk.us-ca.ufileos.com")) return true
    if (url.contains("walk") || url.contains("novel")) return true
    if (url.contains("google")) return false
    if (url.contains("facebook")) return false
    return true
}